<script setup>
	import {
		computed,
		reactive
	} from 'vue'
	import {
		useUserStore
	} from '../../../store/user';
	import {
		imgUrl
	} from '@/utils/global';
	import {
		netConfig
	} from '@/config/net.config';
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import {
		editUserApi
	} from '@/api/user';

	const userStore = useUserStore();

	onLoad(() => {
		formData.name = userStore.userInfo.nickname;
		formData.avatarUrl = userStore.userInfo.avatar;
	});

	// 表单数据
	const formData = reactive({
		name: '',
		avatarUrl: ''
	})

	// 表单验证规则
	const validateForm = () => {
		const errors = []

		// 姓名验证
		if (!formData.name.trim()) {
			errors.push('请输入用户名')
		} else if (!/^[\u4e00-\u9fa5]{2,15}$/.test(formData.name)) {
			errors.push('用户名请输入2-15个中文字符')
		}

		return errors
	}

	// 保存表单
	const handleSave = async () => {
		const errors = validateForm()

		if (errors.length > 0) {
			uni.showToast({
				title: errors[0],
				icon: 'none',
				duration: 2000
			})
			return
		}

		try {
			await editUserApi({
				id: userStore.userInfo.id,
				avatar: formData.avatarUrl,
				nickname: formData.name
			});

			await userStore.getUserInfo();
			formData.avatarUrl = userStore.userInfo.avatar;
			formData.name = userStore.userInfo.nickname;

			uni.showToast({
				title: '保存成功',
				icon: 'success',
				duration: 1000
			});
			setTimeout(() => {
				uni.navigateBack(-1);
			}, 1000);
		} catch (error) {
			console.error('handleSave error', error);
			uni.showToast({
				title: '保存失败',
				icon: 'error'
			});
		}
	}

	const handleChooseAvatar = async (event) => {
		const avatarUrl = event.detail.avatarUrl;

		if (!avatarUrl) {
			uni.showToast({
				title: '未选择头像',
				icon: 'error'
			});
			return;
		}

		formData.avatarUrl = avatarUrl;

		uni.uploadFile({
			url: netConfig.baseURL + '/member/uploadimg',
			filePath: avatarUrl,
			name: 'name',
			header: {
				token: userStore.token
			},
			success: (res) => {
				if (res.statusCode !== 200) {
					uni.showToast({
						title: '上传头像失败',
						icon: 'none'
					});
					return;
				}
				const data = JSON.parse(res.data);
				const avatarUrl = data.data.url;
				formData.avatarUrl = avatarUrl;
			},
			fail: (error) => {
				console.error('uploadAvatar error', error);
				uni.showToast({
					title: '上传头像失败',
					icon: 'none'
				});
			}
		})
	}
	const logout = () => {
		uni.showModal({
			title: '提示',
			content: '确定要退出登录吗',
			success(res) {
				if (res.confirm) {
					userStore.clearLogin()
					uni.showToast({
						title:"退出成功",
						icon:"none"
					})
					setTimeout(()=>{
						uni.switchTab({
							url: '/pages/index/index'
						});
					},500)
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
	}
	const getPreviewAvatar = computed(() => {
		if (formData.avatarUrl) {
			if (formData.avatarUrl.includes('/uploads')) return imgUrl(formData.avatarUrl);
			return formData.avatarUrl;
		} else {
			return imgUrl('/static/img/imgs/avatar_empty.png');
		}
	})

	const handleNameChange = (event) => {
		formData.name = event.detail.value;
	}
</script>

<template>
	<view class="app-edit">
		<view class="edit-form">
			<view class="form-title">
				<text>*</text>
				<text>个人资料</text>
			</view>
			<view class="form-content">
				<view class="form-avatar">
					<text>头像</text>
					<view class="avatar-row">
						<button open-type="chooseAvatar" @chooseavatar="handleChooseAvatar">
							<image class="form-avatar" :src="getPreviewAvatar" mode="aspectFit" />
						</button>
					</view>
				</view>

				<view class="form-input">
					<text>用户名</text>
					<input type="nickname" placeholder="请输入用户名" @change="handleNameChange" v-model="formData.name" />
				</view>
			</view>
		</view>

		<view class="save-button" @click="handleSave">
			<text>保存</text>
		</view>

		<view class="save-button logout-button" @click="logout">
			<text>退出登录</text>
		</view>
	</view>
</template>

<style src="./style.scss" scoped />